<script setup lang="ts">
import { getFils, uploadLocalLogs } from '@/utils/cosUpload';
import { getCurrentInstance, onMounted, ref } from 'vue';

defineProps<{
  msg: string
}>()

const _axios = getCurrentInstance()?.appContext.config.globalProperties.$http;
const indexDBApi = getCurrentInstance()?.appContext.config.globalProperties.$indexDBApi;

onMounted(async () => {
  // setName();
  getLogs();
});

const getFilsForJson = () => {
  //get 请求
  _axios.get("/hy_client_log/2024_10_17_16_30_27_log_api.json?d=" + new Date().getTime()).then((response: any) => {
    // console.log(JSON.parse(response.data.items));
  });
  //post 请求
  _axios.post("/hy_client_log/upload_log", { name: "zgz" }).then((response: any) => {
    // console.log(response.data);
  });
}


const logsFiles = ref<string[]>([]);
const getLogs = () => {
  getFils((items: any) => {
    items.forEach((item: any) => {
      if (item.Size != 0) {
        logsFiles.value.push(item.Key);
      }
    });
  });
};

const getDowloadApiLog = () => {
  indexDBApi.getAllData().then((res: any[]) => {
    uploadLocalLogs(JSON.stringify(res), `${indexDBApi.dbName}_${indexDBApi.storeName}`, (path: string) => {
      console.log("API日志下载成功，路径：" + path);
    });
  });
};

const getApiLog = () => {
  logsFiles.value.filter(item => item.includes('store_api')).forEach(item => {
    getLogFile(item);
  });
}
const getJsLog = () => {
  logsFiles.value.filter(item => item.includes('store_js')).forEach(item => {
    getLogFile(item);
  });
}


const activeLog = ref<any[]>([]);
const getLogFile = (url: string) => {
  _axios.get(url + "?d=" + new Date().getTime()).then((data: any) => {
    var res = JSON.parse(data.data.items);
    res.map((item: any) => {
      item.creatDateTime = new Date(item.creatDateTime).toLocaleString();
      return item;
    });
    activeLog.value = res;
  });
}
</script>

<template>
  <div class="greetings">
    <h1 class="green">{{ msg }}</h1>
    <button @click="getFilsForJson">调用接口</button>
    <button style="margin-left: 10px;" @click="getLogs">获取日志</button>
    <button style="margin-left: 10px;" @click="getDowloadApiLog">下载本地日志</button>

    <h1 style="padding-top: 30px;">日志列表</h1>
    <hr />
    <div style="padding-top: 10px;">
      <button @click="getApiLog">接口异常日志</button>
      <button @click="getJsLog" style="margin-left: 10px;">JS异常日志</button>
    </div>
    <h3 style="padding-top: 10px;">日志内容</h3>
    <ul>
      <li style="width: 100%;overflow-x: auto;" v-for="item in activeLog" :key="item">
        <pre style="width: 100%;overflow-x: auto;background-color: #000;color: #fff;"> <code>{{ item }}</code></pre>
      </li>
    </ul>
  </div>
</template>

<style scoped>
h1 {
  font-weight: 500;
  font-size: 2.6rem;
  position: relative;
  top: -10px;
}

button {
  cursor: pointer;
}

h3 {
  font-size: 1.2rem;
}

.greetings h1,
.greetings h3 {
  text-align: center;
}

@media (min-width: 1024px) {

  .greetings h1,
  .greetings h3 {
    text-align: left;
  }
}
</style>
